package com.cloud.lb.controller;

import com.cloud.domain.TOrder;
import com.cloud.lb.server.impl.MyLoadBalancer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

/**
 * 自定义负载均衡策略的生效需要将注入的restTemplate上的@LoadBalanced注解去掉
 */
//@RestController
public class LbController {

    @Resource
    private DiscoveryClient discoveryClient;

    @Autowired
    private MyLoadBalancer myLoadBalancer;

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/lbIndex")
    public TOrder lbIndex(Long id) {
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PRODUCER");
        ServiceInstance target = myLoadBalancer.instances(instances);
        String uri = target.getUri() + "/domain/t-order/getById?id=%d";

        String formatUrl = String.format(uri, id);
        ResponseEntity<TOrder> forEntity = restTemplate.getForEntity(formatUrl, TOrder.class);
        if (forEntity.getBody() != null) {
            TOrder body = forEntity.getBody();
            return body;
        }
        return null;
    }

}
